/* INCLUDES ******************************************************************/

#include "ses_button.h"
#include <avr/interrupt.h>

#include"ses_common.h"
#include<avr/io.h>
#include"ses_led.h"
#include "ses_scheduler.h"

/*Macros**********************************************************************/
#define EXPIRE_BUTTON   150
#define PEROID_BUTTON   0
/* PRIVATE VARIABLES *********************************************************/
pButtonCallback joystickCallback, RotaryCallback;
volatile uint8_t trigger=0;
/* FUNCTION DEFINITION *******************************************************/

/**
 * Initialize Joystick and Rotary  buttons
 */
void button_init() {
	DDR(BUTTON_ROTARY_PORT) &= ~(1 << BUTTON_ROTARY_PIN);
	DDR(BUTTON_JOYSTICK_PORT) &= ~(1 << BUTTON_JOYSTICK_PIN);
	BUTTON_ROTARY_PORT |= (1 << BUTTON_ROTARY_PIN);
	BUTTON_JOYSTICK_PORT |= (1 << BUTTON_JOYSTICK_PIN);
	PCICR |= (1 << PCIE0);
	PCMSK0 |= (1 << BUTTON_ROTARY_PIN) | (1 << BUTTON_JOYSTICK_PIN);
}

/**Sets callback for rotary encoder button pressed event
 *
 * @param callback	a valid pointer to callback function or NULL to
 *			          deactivate the callback
 */
void button_setRotaryButtonCallback(pButtonCallback callback) {
	RotaryCallback = callback;
}

/**
 *Sets callback for joystick button pressed event
 *
 * @param callback 	a valid pointer to callback function or NULL to
 *			        deactivate the callback
 */
void button_setJoystickButtonCallback(pButtonCallback callback) {
	joystickCallback = callback;
}
void checkbutton() {
    trigger=1;


}
/**
 * Interrupt service routine for pin change interrupt 7:0
 */ISR(PCINT0_vect) {
	 if(trigger==0){
	scheduler_add(checkbutton, EXPIRE_BUTTON, PEROID_BUTTON);

	 }
	 if(trigger==1){
	if (!(PIN(BUTTON_ROTARY_PORT) & (1 << BUTTON_ROTARY_PIN))) {
		RotaryCallback();
	}
	if (!(PIN(BUTTON_JOYSTICK_PORT) & (1 << BUTTON_JOYSTICK_PIN))) {
		joystickCallback();
	}
	 trigger=0;}
}

